package org.example.config;

import org.example.model.Menu;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @Author: LiFuqiang
 * @Date: 2020/9/29 15:14
 * @Version 1.0
 * @description
 */
@Component
public class CustomFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        String requestUrl = ((FilterInvocation) object).getRequestUrl();
        List<Menu> menus = getAllMenusWithRole();
        for (Menu menu : menus) {
            if (antPathMatcher.match(menu.getUrl(), requestUrl)) {
                List<String> roles = menu.getRoles();
                String[] str = new String[roles.size()];
                for (int i = 0; i < roles.size(); i++) {
                    str[i] = roles.get(i);
                }
                return org.springframework.security.access.SecurityConfig.createList(str);
            }
        }
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }

    public List<Menu> getAllMenusWithRole(){
        List<Menu> list = new ArrayList<>();

        Menu menu1 = new Menu();
        menu1.setUrl("/addHost");
        List<String> list1 = new ArrayList<String>();
        list1.add("admin");
        menu1.setRoles(list1);
        list.add(menu1);

        Menu menu2 = new Menu();
        menu2.setUrl("/executeCmd/hadoop/**");
        List<String> list2 = new ArrayList<String>();
        list2.add("hadoop");
        list2.add("admin");
        menu2.setRoles(list2);
        list.add(menu2);

        Menu menu3 = new Menu();
        menu3.setUrl("/executeCmd/kafka/**");
        List<String> list3 = new ArrayList<>();
        list3.add("kafka");
        list3.add("admin");
        list.add(menu3);

        return list;
    }

    public static void main(String[] args) {
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        System.out.println(antPathMatcher.match("/executeCmd/kafka/**","/executeCmd/kafka/start/br/jj"));
    }
}
